package cn.wonhigh.o2o.openfire.plugins;

import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;

import org.jivesoftware.openfire.MessageRouter;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.roster.Roster;
import org.jivesoftware.openfire.roster.RosterItem;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.util.JiveGlobals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;

import cn.wonhigh.o2o.openfire.plugins.intercepter.MessageTransmitInterceptor;

import com.alibaba.fastjson.JSON;

/**
 * 会员积分联盟消息处理插件.
 * 
 * @author yu.jz
 * @date 2014-7-18 上午9:36:14
 * @version 0.1.0
 * @copyright yougou.com
 */
public class MessagePlugin implements Plugin {

	private static final Logger LOG = LoggerFactory
			.getLogger(MessagePlugin.class);
	private XMPPServer server;
	private MessageRouter messageRouter;
	private String domain;
	private static final String MESSAGE_TYPE_LOGO = "logo";

	private PacketInterceptor interceptor = null;
	private InterceptorManager interceptorManager = null;
	private UserManager userManager;

	@Override
	public void destroyPlugin() {
		if (interceptor != null) {
			interceptorManager.removeInterceptor(interceptor);
			interceptor = null;
		}
		interceptorManager = null;
		server = null;
	}

	@Override
	public void initializePlugin(PluginManager manager, File pluginDirectory) {
		LOG.info("初始化消息处理插件");

		server = XMPPServer.getInstance();
		userManager = server.getUserManager();
		messageRouter = server.getMessageRouter();
		domain = JiveGlobals.getProperty("xmpp.domain");

		String transmitURL = JiveGlobals.getProperty("plugin.message.url");
		interceptor = new MessageTransmitInterceptor(transmitURL);
		interceptorManager = InterceptorManager.getInstance();
		interceptorManager.addInterceptor(interceptor);

		LOG.info("消息处理插件加载成功");
	}
	
	private User getUser(String username) throws UserNotFoundException {
        JID targetJID = server.createJID(username, null);
        if (targetJID.getNode() == null) {
            throw new UserNotFoundException("Username("+username+") not found");
        }
        return userManager.getUser(targetJID.getNode());
    }

	public String sendMessage(String from, String to, String msg) {
		try {
			@SuppressWarnings("unchecked")
			Map<String, String> message = JSON.parseObject(msg, Map.class);
			if(null != message && MESSAGE_TYPE_LOGO.equals(message.get("type"))) {
				LOG.info("门店修改logo，from={}, to={}, msg={}", new Object[]{from, to, msg});
				// 门店logo改变，给好友群发消息
				User user = getUser(from);
				sendMessage2(from, from, msg); // 发给自己，通知logo已经改变
				Roster roster = user.getRoster();
				LOG.info("门店修改logo，给好友发送消息:roster={}", roster);
				if(null != roster) {
					Collection<RosterItem> rosterItems = roster.getRosterItems();
					LOG.info("rosterItems");
					if(rosterItems != null && rosterItems.size() > 0) {
						for(RosterItem rosterItem : rosterItems) {
							String rosterName = rosterItem.getJid().getNode();
							if(rosterName.length() > 20) {// 说明是关注者
								continue;
							}
							sendMessage2(from, rosterName, msg);
						}
					}
				}
				return "ok";
			}
		} catch (Exception e) {
			return e.getMessage();
		}
		
		return sendMessage2(from, to, msg);
	}
	
	private String sendMessage2(String from, String to, String msg) {
		Message message = new Message();
		message.setFrom(new JID(from + "@" + domain));
		message.setTo(new JID(to + "@" + domain));
		message.setBody(msg);
		message.setType(Message.Type.chat);
		message.setID(UUID.randomUUID().toString());
		LOG.info("转发给店员的XMPP：{}", message.toString());
		messageRouter.route(message);
		return "ok";
	}

}
